package com.veromca.substitution.consumer;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.veromca.mqclient.TransactionMqRemoteClient;
import com.veromca.substitution.po.TransactionOrderDto;
import com.veromca.substitution.service.IWarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.TextMessage;

/**
 * @Description:消息消费类
 * @Author: liusongqing
 * @CreateDate: 2019/12/03
 * @UpdateUser:
 * @UpdateDate:
 * @Copyright:
 * @UpdateRemark:
 * @Version: 0.2
 */
@Component
public class ActiveMqConsumer {
    @Autowired
    private TransactionMqRemoteClient transactionMqRemoteClient;
    @Autowired
    private IWarehouseService warehouseService;

    //消息队列监听
    @JmsListener(destination = "order_queue")
    public void receiveQueue(TextMessage text) {
        try {
            System.out.println("可靠消息服务消费消息：" + text.getText());
            //throw new RuntimeException("");
            // 1.消费方自身业务处理
            JSONObject msgObj = JSONObject.parseObject(text.getText());
            Object msg = msgObj.get("message");
            TransactionOrderDto dto = JSON.toJavaObject(JSON.parseObject(msg.toString()),TransactionOrderDto.class);
            warehouseService.update(dto);
            // 2.调用可靠性消息服务修改消息状态为已消费，消息成功消费
            boolean result = transactionMqRemoteClient.confirmCustomerMessage("substitution-server", Integer.valueOf(msgObj.get("messageId").toString()));
            // 3.手动 ack 通知队列消息已成功消费不再重发
            if (result) {
                text.acknowledge();
            }
        } catch (Exception e) {
            // 异常会触发重试机制，重试次数完成之后还是错误，消息会进入DLQ队列中
            throw new RuntimeException(e);
        }
    }

}
